@file:OptIn(DelicateCoroutinesApi::class)

package com.capa.net

import com.capa.model.DeepSeekRequest
import com.capa.model.DeepSeekResponse
import com.capa.model.PhoneLoginRequest
import com.capa.network.ApiService
import com.capa.network.BaseResponse
import com.capa.network.ExceptionUtil
import com.capa.network.RetrofitClient
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

/**
 * 请求管理类
 */
class DataService {
    companion object {
        suspend fun getCaptcha(host: Int, phoneNumber: String): BaseResponse<Any> {
            return RetrofitClient.getInstance().getDefault(ApiService::class.java, host)
                .getCaptcha(phoneNumber)
        }

        suspend fun phoneLogin(host: Int, phoneNumber: String, captcha: String): BaseResponse<Any> {

            return RetrofitClient.getInstance().getDefault(ApiService::class.java, host)
                .phoneLogin(PhoneLoginRequest(phoneNumber, captcha))
        }

        suspend fun requestDeepSeek(host: Int, request: DeepSeekRequest): DeepSeekResponse {
            return RetrofitClient.getInstance().getDefault(ApiService::class.java, host)
                .requestDeepSeek(request)
        }

        fun launch(
            block: suspend CoroutineScope.() -> Unit,
            onError: (e: Throwable) -> Unit = { _: Throwable -> },
            onComplete: () -> Unit = {}
        ) {
            GlobalScope.launch(
                CoroutineExceptionHandler { _, throwable ->
                    run {
                        // 这里统一处理错误
                        ExceptionUtil.catchException(throwable)
                        onError(throwable)
                    }
                }
            ) {
                try {
                    block.invoke(this)
                } finally {
                    onComplete()
                }
            }
        }
    }
}